package unamur.iodass.catalog;

import java.util.ArrayList;

import org.apache.log4j.Logger;

import unamur.iodass.accountancy.Accountancy;
import unamur.iodass.communication.Communication;
import unamur.iodass.communication.messages.Book;
import unamur.iodass.communication.messages.Catalog;
import unamur.iodass.data.CatalogData;

public class CatalogHandler {
	private static final Logger logger = Logger.getLogger(CatalogHandler.class);
	
	private static volatile CatalogHandler instance;
	
	
	Catalog catalog;
	Communication com;
	
	
	public static CatalogHandler getInstance() {
		if (instance == null) {
			synchronized (CatalogHandler.class) {
				if (instance == null) {
					instance = new CatalogHandler();
				}
			}
		}
		return instance;
	}
	
	
	private CatalogHandler() {
		com = Communication.getInstance(); 
		
		CatalogData data = new CatalogData();
		ArrayList<Book> books = data.getBooks();
		catalog = new Catalog(books);
	}
	
	public void sendCatalogToServer() {
		if (catalog != null) {
			com.async(catalog, com.ONLINELIBRARY_IP, com.ONLINELIBRARY_PORT);
		}else {
			logger.error("Catalog est null et ne peut donc pas être envoyé à OnlineLibrary");
		}
	}
	
	public Catalog getCatalog() {
		return catalog;
	}
	
	public boolean estDisponible(long isbn) {
		boolean dispo = false;
		for (int i=0; i<catalog.getSize() && (!dispo); i++) {
			if (catalog.getBooks().get(i).getIsbn() == isbn) {
				return true;
			}
		}
		
		return false;
	}
}
